﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;
using log4net;
using Runda.CMS.Common.Log; 
namespace Runda.CMS.Portal
{
    public class BasePage:Page
    {
        #region 属性

        /// <summary>
        /// 当前登录用户
        /// </summary>
        protected Guid CurrentUserID
        {
            get
            {
                if (Session[DeclareHelper.SessionConstant.CurrentUserID] == null)
                {
#if DEBUG
                    Session[DeclareHelper.SessionConstant.CurrentUserID] = new Guid("11111111-1111-1111-1111-111111111111");//admin
                    //Session[DeclareHelper.SessionConstant.CurrentUserID] = new Guid("411CB239-A380-43C9-BCE2-C7F8FD5D9A58");//sales
                    //Session[DeclareHelper.SessionConstant.CurrentUserID] = new Guid("0AB57A13-8527-491F-B255-A584979226C1");//finance
                    //Session[DeclareHelper.SessionConstant.CurrentUserID] = new Guid("E7876713-4E3F-449B-B4F9-7215AFAB7F25");//direct
                    return new Guid(Session[DeclareHelper.SessionConstant.CurrentUserID].ToString());
#else
                    return Guid.Empty;
#endif
                }
                else
                {
                    return new Guid(Session[DeclareHelper.SessionConstant.CurrentUserID].ToString());
                }
            }
        }

        /// <summary>
        /// 当前用户实体
        /// </summary>
        protected SysUserEntity CurrentUserEntity
        {
            get
            {
                try
                {
                    if (HttpContext.Current.Session[DeclareHelper.SessionConstant.CurrentUserEntity] == null)
                    {
                        HttpContext.Current.Session[DeclareHelper.SessionConstant.CurrentUserEntity] = new SysUserBll().Get<SysUserEntity>(CurrentUserID);
                    }

                    SysUserEntity sessionUser = (SysUserEntity)Session[DeclareHelper.SessionConstant.CurrentUserEntity];

                    return sessionUser;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 是否判断权限信息
        /// 对于登录用户均可访问的页面可设置该值为false，以避免不需要的权限配置
        /// </summary>
        public virtual bool IsCheckAccessible
        {
            get
            {
                return true;
            }
        }

        private string CurrentAppPath
        {
            get
            {
                string appPath = Request.RawUrl.ToLower();

                if (Request.ApplicationPath.ToLower() != "/")
                {
                    appPath = appPath.Replace(Request.ApplicationPath.ToLower(), "");
                }

                if (appPath.Contains("?"))
                {
                    appPath = appPath.Substring(0, appPath.IndexOf("?"));
                }
                return appPath.TrimStart('/');
            }
        }

        private bool HasPermission
        {
            get 
            {
                if (!string.IsNullOrEmpty(CurrentAppPath) && CurrentAppPath.ToLower() != "./default")
                {
                    return new SystemBll().CheckUserHasFuction(CurrentUserID, 0, CurrentAppPath);
                }
                return true;       
            }
        }

        #endregion

        #region Override Methods

        protected override void OnLoad(EventArgs e)
        {
            if (this.CurrentUserID == null || CurrentUserID == Guid.Empty)
            {
                string url = Request.ApplicationPath + "/Error.aspx?Error=" + ((int)Enumerator.ErrorType.SessionAbandon).ToString();
                url = url.Replace("//", "/");
                Response.Redirect(url);
            }
            else
            {
                if (IsCheckAccessible)
                {
                    if (!HasPermission)
                    {
                        string url = Request.ApplicationPath + "/Error.aspx?Error=" + ((int)Enumerator.ErrorType.NoRight).ToString();
                        url = url.Replace("//", "/");
                        Response.Redirect(url);
                    }
                }
            }
                base.OnLoad(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void OnError(EventArgs e)
        {            
            base.OnError(e);

            string errUrl = Request.Url.Authority + Request.ApplicationPath + "/Error.aspx?Error=0";
            Exception ex = Server.GetLastError() as Exception;
     
             ILog logger = log4net.LogManager.GetLogger("myLogger");
             logger.Error(new LogContent(LogType.err, "Error", CurrentUserID.ToString(), "", "错误信息:"+ex.Message));
          
            errUrl = errUrl.Replace("//", "/");

            errUrl = "http://" + errUrl;

            Response.Redirect(errUrl);

        }

        #endregion

        #region public methods
        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="CheckType">类型：0 by url,1 by function code</param>
        /// <param name="CheckObject"></param>
        /// <returns></returns>
        public bool CheckUserHasFuction(int CheckType,string CheckObject)
        {
            SystemBll bll = new SystemBll();
            return bll.CheckUserHasFuction(CurrentUserID, CheckType, CheckObject);
        }
        #endregion

        #region Private Methods

        #endregion
    }
}
